#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
#include<unistd.h>
#include<string.h>

/*
 *  
	success fd = 3
	write count = 11
	read buf2= hello worldhello worldhello worl
	（这里地址刚好后面是\0,所以没有出现乱码，为保险起见，加入了buf2[31]='\0'）,打印如下

	success fd = 3
	write count = 11
	read buf2= hello worldhello worldhello wor
 *
 */

int main(){
	int ret;
	int fd = open("test.txt", O_RDWR|O_CREAT|O_APPEND, 0666);
	if(fd < 0){
		perror("open file");
		return 0;
	}
	printf("success fd = %d\n", fd);

	//往文件写
	char buf[32] = "hello world";
	char buf2[32] = {0};
	ret = write(fd, buf, strlen(buf));
	if(ret < 0){
		perror("write");
		goto END;
	}
	printf("write count = %d\n", ret);

	//移动文件指针
	lseek(fd, 0, SEEK_SET);

	//从文件读
	ret = read(fd, buf2, 32);
	if(ret < 0){
		perror("read");
		goto END;
	}
	//为确保字符串能正常输出 需要将最后一个字符给置为\0,避免出现未知错误
	buf2[31]='\0';
	printf("read buf2= %s\n", buf2);

END:
	//关闭文件
	ret = close(fd);
	if(ret < 0){
		perror("close failed");
	}
}

